<template>
	<view>
		<view class="page__content">
			<up-navbar :fixed="false" title="工单" :autoBack="true" :safeAreaInsetTop="true"
				leftIconColor="#fff"></up-navbar>

			<view class="page__content__main">
				<up-form labelPosition="left" :model="formData" :rules="rules" ref="baseFormRef">
					<up-form-item labelWidth="120" label="工单编号" :borderBottom="true" leftIcon="order"
						:leftIconStyle="{'font-size':'40rpx'}">
						<view class="iptView">
							<up-input v-model="formData.BillNO" placeholder="自动生成" readonly border="none"></up-input>
						</view>
					</up-form-item>

					<up-form-item labelWidth="120" label="产品名称" prop="ProductName" :borderBottom="true"
						leftIcon="file-text" required :leftIconStyle="{'font-size':'40rpx'}">
						<view class="iptView" @click="openBaseScreen('产品','radio')">
							<up-input v-model="formData.ProductName" readonly placeholder="请选择"
								border="none"></up-input>
						</view>
						<template #right>
							<up-icon name="arrow-right" size="18"></up-icon>
						</template>
					</up-form-item>

					<up-form-item labelWidth="120" label="工艺路线" prop="Routing" :borderBottom="true" leftIcon="share"
						required :leftIconStyle="{'font-size':'40rpx'}">
						<view class="iptView" @click="openBaseScreen('工艺路线','other')">
							<up-input v-model="formData.Routing" readonly placeholder="请选择" border="none"></up-input>
						</view>
						<template #right>
							<up-icon name="arrow-right" size="18"></up-icon>
						</template>
					</up-form-item>

					<up-form-item labelWidth="120" label="工作中心" prop="FWorkshopName" :borderBottom="true"
						leftIcon="file-text" required :leftIconStyle="{'font-size':'40rpx'}">
						<view class="iptView" @click="openBaseScreen('工作中心','radio')">
							<up-input v-model="formData.FWorkshopName" readonly placeholder="请选择"
								border="none"></up-input>
						</view>
						<template #right>
							<up-icon name="arrow-right" size="18"></up-icon>
						</template>
					</up-form-item>

					<up-form-item labelWidth="120" label="是否线性" prop="IsLinear" :borderBottom="true"
						leftIcon="file-text" required :leftIconStyle="{'font-size':'40rpx'}">
						<view class="iptView" @click="openBaseScreen('线性','radio')">
							<up-input v-model="formData.IsLinear" readonly placeholder="请选择" border="none"></up-input>
						</view>
						<template #right>
							<up-icon name="arrow-right" size="18"></up-icon>
						</template>
					</up-form-item>

					<up-form-item labelWidth="120" label="计划数" prop="FPlanQty" :borderBottom="true" leftIcon="coupon"
						required :leftIconStyle="{'font-size':'40rpx'}">
						<view class="iptView">
							<up-input v-model="formData.FPlanQty" type="number" placeholder="请输入"
								border="none"></up-input>
						</view>
						<template #right>
							<up-icon name="edit-pen-fill" color="#999" size="18"></up-icon>
						</template>
					</up-form-item>


					<up-form-item labelWidth="120" label="计划开始时间" :borderBottom="true" leftIcon="coupon" required
						:leftIconStyle="{'font-size':'40rpx'}">
						<view class="iptView" @click="choiceTime('start')" style="font-size: 28rpx;">
							<text>{{dateFormat(formData.StartTime) }}</text>
						</view>
						<template #right>
							<up-icon name="calendar" color="#999" size="18"></up-icon>
						</template>
					</up-form-item>
					<up-form-item labelWidth="120" label="计划结束时间" :borderBottom="true" leftIcon="coupon" required
						:leftIconStyle="{'font-size':'40rpx'}">
						<view class="iptView" @click="choiceTime('end')" style="font-size: 28rpx;">
							<text>{{dateFormat(formData.EndTime) }}</text>
						</view>
						<template #right>
							<up-icon name="calendar" color="#999" size="18"></up-icon>
						</template>
					</up-form-item>


					<up-form-item labelWidth="120" style="margin-top: 10px;" :borderBottom="true" label="用料清单"
						leftIcon="file-text" :leftIconStyle="{'font-size':'40rpx'}"
						@click="openBaseScreen('用料清单','other')">
						<view v-if="formData.MaterialsListTotal" class="create-ticket__materials">
							<text>共需</text>
							<text class="create-ticket__materials-count">{{formData.MaterialsListTotal}}</text>
							<text>种物料</text>
						</view>
						<view v-else class="create-ticket__materials-empty">
							<text>暂无用料</text>
						</view>
						<template #right>
							<up-icon name="arrow-right" size="18"></up-icon>
						</template>
					</up-form-item>

					<up-form-item labelWidth="120" label="附件" prop="Filepath" leftIcon="coupon"
						:leftIconStyle="{'font-size':'40rpx'}">
						<view style="width: 100%;">
							<m-upload v-model="uploadFile_list" useBeforeDelete
								:listStyle="{columns: BoxInfoCallBack.num,height:BoxInfoCallBack.height+'rpx',padding:'6px',columnGap:'10px',rowGap:'10px'}"
								@beforeDelete="beforeDelete" cloudType="other" :action="uploadFile_action"
								@onSuccess="onSuccess"></m-upload>
						</view>
					</up-form-item>

					<up-form-item labelWidth="120" label="备注" prop="Comment" leftIcon="coupon"
						:leftIconStyle="{'font-size':'40rpx'}">
						<view class="iptView" style="padding: 10px 20px 0;width: 100%;">
							<up-textarea v-model="formData.Comment" placeholder="请输入内容" count
								maxlength="150"></up-textarea>
						</view>
					</up-form-item>
				</up-form>

			</view>
			<view class="page__content__bottom" :style="uni.$utils.disposeSafeBottomFun()">
				<button :disabled="!enabledSubmitBtn" v-if="formData.WoOrderID == 0"
					class="content_bottom_primary_Btn page__content__bottom__btn" @click="saveRow('create')">提交</button>

				<view v-else-if="formData.WoOrderID != 0 && !formData.Approve" class="x-ec" style="width: 100%;">
					<button :disabled="!enabledSubmitBtn" v-if="ApproveBack('审核')"
						class="content_bottom_primary_plainBtn page__content__bottom__btn"
						@click="saveRow('Audit')">审核</button>
					<button :disabled="!enabledSubmitBtn" v-if="ApproveBack('修改')"
						class="content_bottom_primary_Btn page__content__bottom__btn"
						@click="saveRow('edit')">提交</button>
				</view>


				<view v-else-if="formData.WoOrderID != 0 && formData.Approve" class="x-ec" style="width: 100%;">
					<button :disabled="!enabledSubmitBtn" v-if="FCJType == 1"
						class="content_bottom_primary_Btn page__content__bottom__btn"
						@click="openDispatchBtn">发放派工</button>
					<button :disabled="!enabledSubmitBtn" v-if="ApproveBack('撤审')"
						class="content_bottom_primary_plainBtn page__content__bottom__btn"
						@click="onAuditBtn('btn')">撤审</button>
				</view>
			</view>
		</view>

		<!-- 时间选择器 -->
		<up-datetime-picker ref="datetimePicker" :title="PickerTitle" :show="showTimePicker" v-model="DatetimeData"
			mode="date" :closeOnClickOverlay="true" @close="closePicker" @cancel="closePicker" @confirm="confirmTime"
			:formatter="formatterByTimePicker"></up-datetime-picker>

		<!-- 加载动画 -->
		<m-loading :text="loadingConfig.text" :value="loadingConfig.show" :showClose="false"
			maskBackgroundColor="rgba(0,0,0,0.3)"></m-loading>
	</view>
</template>

<script setup lang="ts">
	import { ref, reactive, onMounted, computed } from 'vue'
	import { onLoad, onReady, onShow, onUnload } from '@dcloudio/uni-app'
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, PromiseRequestByUrl, onAllComplete, onError } = useRequestQueue();
	import { useMainStore, useUserStore, usePermissionStore, useTicketStore } from '@/store';
	const mainStore = useMainStore();
	const userStore = useUserStore();
	const permissionStore = usePermissionStore();
	const ticketStore = useTicketStore();

	// import mClUpload from '@/st_ticket/components/cl-upload/components/cl-upload/cl-upload'
	// import mClUpload from '@/commonPage/components/cl-upload/cl-upload';

	defineOptions({
		options: {
			styleIsolation: 'shared'
		}
	})

	let enabledSubmitBtn = ref(false);
	let loadingConfig = reactive({
		text: "正在渲染",
		show: false,
	})

	const FCJType = computed(() => {
		return ticketStore.FCJType;
	})


	interface UFormsInstance {
		validate : (callback ?: (isValid : boolean) => void) => Promise<boolean>
		resetFields : () => void;
		setRules : any;
	}
	const baseFormRef = ref<UFormsInstance | any>(null);
	let formData = reactive<any>({
		WoOrderID: 0,

		BillNO: '', // 产品编号
		ProductName: '', // 产品名称
		ProductCode: '',
		ProductID: '',

		Routing: '', // 工艺路线

		FWorkshopName: '', // 工作中心
		FWorkshopID: '', // 工作中心

		IsLinear: '', // 是否线性
		IsLinearID: '',

		FPlanQty: null, // 计划数
		AbnormalReport: '', // 异常报工
		MaterialsListTotal: '', // 用料清单
		AnnexList: [], // 附件
		FilePath: '', // 附件地址
		Comment: '', // 备注

		StartTime: new Date(), // 开始时间,
		EndTime: new Date(), // 结束时间
	});
	// 文件上传
	let uploadFile_list = ref<any>([]);
	let BoxInfoCallBack = reactive({
		num: 3,
		height: 100
	});
	const screenWidth = mainStore.systemConfig.sysDeviceInfo.screenWidth;
	const backNumByWidth = uni.$utils.calculateAdaptiveLayout(screenWidth, 20);
	console.log(backNumByWidth);
	Object.assign(BoxInfoCallBack, backNumByWidth);

	// 获取资源平台地址
	const ip_info = computed(() => {
		return mainStore.appConfigInfo.ICPServerIP;
		// return mainStore.appConfigInfo.IPAgreement + mainStore.appConfigInfo.serverIP;
	})
	const uploadFile_action = computed(() => {
		return mainStore.appConfigInfo.IPAgreement + mainStore.appConfigInfo.serverIP + "/FileData/UploadSignleFile";
	});
	function beforeDelete({
		fileToDelete,
		uploadKey
	}, index : number, next : () => void) {

		uni.$utils.layer.confirm('确定要删除这个文件嘛？', {
			title: '提示信息',
		}, function ({ action }) {
			switch (action) {
				case 'confirm':
					uploadFile_list.value.splice(index, 1);
					let arr = formData.FilePath.split(",");
					arr.splice(index, 1);
					formData.FilePath = arr.join(",");

					// 模拟服务器接口
					setTimeout(() => {
						next();
					}, 300);
					break;
				case 'cancel':
					break;
				default:
					break;
			}
		})

	};
	function onSuccess(data : any) {
		console.log(data);
		uni.$utils.layer.alert(JSON.stringify(data))
		// let path = ip_info.value + data.data;

		let port = mainStore.appConfigInfo.serverIP.split(':')[1];
		let path = ip_info.value + data.data.replace(/upload/, 'upload/' + port);

		// 给文件上传数据源插入地址
		uploadFile_list.value.push({
			path: path
		});
		// 给主表FilePath字段插入数据
		// 判断是否存在数据
		if (!formData.FilePath) {
			formData.FilePath = data.data;
		} else {
			formData.FilePath += "," + data.data;
		}
	};

	let rules = {
		'ProductName': {
			type: 'string',
			required: true,
			message: '产品不能为空',
			trigger: ['change']
		},
		'Routing': {
			type: 'string',
			required: true,
			message: '工艺路线不能为空',
			trigger: ['change']
		},
		'FWorkshopName': {
			type: 'string',
			required: true,
			message: '工作中心不能为空',
			trigger: ['change']
		},
		'IsLinear': {
			type: 'string',
			required: true,
			message: '是否线性不能为空',
			trigger: ['change']
		},
		'FPlanQty': {
			type: 'number',
			required: true,
			message: '计划数不能为空',
			trigger: ['change']
		},
	};

	let foundNode = ref<any>(null);
	// 获取页面按钮权限
	for (const module of permissionStore.moduleInfoAll) {
		if (module.TreeTypeName === '生产管理') {
			for (const node of module.Node) {
				if (node.APFunName === '新建工单') {
					foundNode.value = JSON.parse(JSON.stringify(node));
					break; // 找到后立即退出内层循环  
				}
			}
			if (foundNode.value) {
				break;
			}
		}
	}
	let btnApprove = ref<any>(null)
	btnApprove.value = uni.$utils.isEmpty(foundNode.value) ? [] : foundNode.value['IconApprove'];

	// 按钮映射
	function ApproveBack(str : string) {
		let Type = btnApprove.value.some((item : any) => {
			return item.MenuName == str
		})

		return Type;
	};



	let routes = getCurrentPages(); //当前页面栈

	const baseScreenListenName = computed(() => {
		return 'createTicet_choice_' + routes.length
	});

	function openBaseScreen(str : string, type : string) {

		switch (type) {
			case "radio":

				switch (str) {
					case "产品":
						mainStore.openBaseScreen({
							allowClear: false, // 清除按钮
							cmd: 'XGD_Product2', // 接口名
							titleName: str,
							listeningName: baseScreenListenName.value, // 监听器
							multiple: false, // 是否开启多选
							enableAddOption: false, // 开启新增
							addOptionPath: "/commonPage/basic-info/create-product", // 新增跳转地址
							serverSearch: { // 查询项
								format: { // 数据映射
									displayValue: "ProductInfo", // 显示值
									hiddenValue: "ProductID", // 隐藏值
									pageIndex: "PageIndex", // 分页状态页码字段
									pageSize: "PageSize", // 分页状态每页数量字段
								},
								isLocal: false, // 是否启用本地数据
								localData: [], // 当开启本地数据时使用
								isPaging: true, //是否分页
								searchKey: 'SearchKey', //搜索关键词，应包含在param中
								// subText: [{
								// 	label: "描述", // label文本
								// 	labelKey: "desc", // 显示label文本后文字的key
								// }],
								// disabled: { // 需要禁用的数据
								// 	data: [], // 基础数组形式
								// 	key: "UserID", // 禁用的对应key
								// },
								choiceData: formData.ProductID, // 选中数据
								choiceDataKey: "ProductID", // 选中数据的key
								isTree: false, // 是否开启树型下拉
							},
							param: { // 传递参数
								SearchKey: '',
								PageIndex: 1,
								PageSize: 30
							}
						});
						break;


					case "工作中心":
						mainStore.openBaseScreen({
							allowClear: false, // 清除按钮
							cmd: 'XGD_Workshop', // 接口名
							titleName: str,
							listeningName: baseScreenListenName.value, // 监听器
							multiple: false, // 是否开启多选
							serverSearch: { // 查询项
								format: { // 数据映射
									displayValue: "FWorkshopName", // 显示值
									hiddenValue: "FWorkshopID", // 隐藏值
									pageIndex: "PageIndex", // 分页状态页码字段
									pageSize: "PageSize", // 分页状态每页数量字段
								},
								isPaging: true, //是否分页
								searchKey: 'SearchKey', //搜索关键词，应包含在param中
								choiceData: formData.FWorkshopID, // 选中数据
								choiceDataKey: "FWorkshopID", // 选中数据的key
							},
							param: { // 传递参数
								SearchKey: '',
								PageIndex: 1,
								PageSize: 30
							}
						});
						break;


					case "线性":
						mainStore.openBaseScreen({
							allowClear: false, // 清除按钮
							cmd: '', // 接口名
							titleName: str,
							listeningName: baseScreenListenName.value, // 监听器
							multiple: false, // 是否开启多选
							serverSearch: { // 查询项
								format: { // 数据映射
									displayValue: "IsLinear", // 显示值
									hiddenValue: "IsLinearID", // 隐藏值
								},
								isLocal: true, // 是否启用本地数据
								localData: [{
									IsLinear: '是',
									IsLinearID: 1
								}, {
									IsLinear: '否',
									IsLinearID: 0
								}], // 当开启本地数据时使用
								isPaging: false, //是否分页
								choiceData: formData.IsLinearID, // 选中数据
								choiceDataKey: "IsLinearID", // 选中数据的key
							},
							param: { // 传递参数
							}
						});
						break;

					default:
						break;
				}


				break;

			case "other":
				switch (str) {
					case "工艺路线":
						// 将当前工艺路线数据存储到pinia中，方便获取

						ticketStore.createTicket_routing = {
							RoutingData: RoutingData.value,
							FWorkshop: {
								FWorkshopName: formData.FWorkshopName,
								FWorkshopID: formData.FWorkshopID,
							},
							formData: formData,
							listenName: baseScreenListenName.value
						};

						uni.navigateTo({
							url: '/st_ticket/page_ticket/choiceRouting'
						})

						break;

					case "用料清单":
						ticketStore.createTicket_Materials = {
							MaterialsList: MaterialsList.value,
							formData: formData,
							listenName: baseScreenListenName.value
						};
						uni.navigateTo({
							url: '/st_ticket/page_ticket/materialsList'
						})
						break;
					default:
						break;
				}



				break;
			default:
				break;
		}


	};

	// 选中的时间类型
	let choiceTimeType = ref<any>(null);
	// 时间选择器时间
	let DatetimeData = ref(Number(new Date()));
	let PickerTitle = ref("");
	let showTimePicker = ref(false);
	// 点击计划时间
	function choiceTime(type : any) {
		choiceTimeType.value = type;

		switch (type) {
			case "start":
				DatetimeData.value = Number(formData.StartTime);
				PickerTitle.value = '计划开始时间';
				break;
			case "end":
				DatetimeData.value = Number(formData.EndTime);
				PickerTitle.value = '计划结束时间';
				break;
			default:
				DatetimeData.value = Number(new Date());
				PickerTitle.value = '';
				break;
		};

		showTimePicker.value = true;
	};
	// 关闭时间选择器
	function closePicker() {
		DatetimeData.value = Number(new Date());
		showTimePicker.value = false;
	};
	// 时间选择器确认
	function confirmTime(data : any) {
		switch (choiceTimeType.value) {
			case "start":
				formData.StartTime = data.value;

				if (Number(formData.EndTime) < Number(data.value)) {
					formData.EndTime = data.value;
				};
				break;
			case "end":
				formData.EndTime = data.value;

				if (Number(formData.StartTime) > Number(data.value)) {
					formData.StartTime = data.value;
				};
				break;
			default:
				break;
		};
		showTimePicker.value = false;
	};

	function formatterByTimePicker(type : any, value : any) { // 时间选择器数据格式化
		let backType = "";
		switch (type) {
			case "year":
				backType = value + "年"
				break;
			case "month":
				backType = value + "月"
				break;
			case "day":
				backType = value + "日"
				break;
			default:
				break;
		}
		return backType;
	}

	function dateFormat(val : any) { // 格式化时间

		if (!uni.$utils.isEmpty(val)) {
			return uni.$utils.dateFormat(new Date(val), 'Y-MM-dd');
		} else {
			return uni.$utils.dateFormat(new Date(), 'Y-MM-dd');
		}
	};

	// 工艺路线数据
	let RoutingData = ref<any>([]);
	// 用料清单
	let MaterialsList = ref<any>([]);

	// 根据产品获取工艺路线、用料清单 
	function ProductToGetInfo() {
		request({
			config: {
			},
			url: 'XGD_SelectBomAndProc2',
			method: 'POST',
			data: {
				ProductID: formData.ProductID
			},
			success(ret : any) {
				console.log(ret);
				if (ret.status == 200) {
					RoutingData.value = ret.data.ds;
					// 拼接工艺路线数据
					let GetRouting = ret.data.ds.map((item : any) => {
						return item.ProcedureName
					})
					formData.Routing = GetRouting.join('、');

					// 提取数据源，减少重复访问
					const firstDsItem = ret.data.ds?.[0];
					// 判断是否存在有效数据
					const hasValidData = ret.data.ds?.length && firstDsItem?.IsLinear !== undefined;
					// 根据条件设置值，使用更简洁的三元表达式
					formData.IsLinearID = hasValidData ? firstDsItem.IsLinear : 0;
					formData.IsLinear = formData.IsLinearID === 1 ? '是' : '否';

					// 用料清单
					MaterialsList.value = ret.data.ds1;
					formData.MaterialsListTotal = ret.data.ds1.length;
					baseFormRef.value?.validate();
				}

			}
		})
	};


	function refreshPage(callBack ?: () => void) {
		// 判断当前状态是否为更新状态
		if (formData.WoOrderID != 0) {
			// 修改工单——查询工单信息

			request({
				config: {
				},
				url: 'XGD_SelectWoOrder',
				method: 'POST',
				data: {
					WoOrderID: formData.WoOrderID
				},
				success(ret : any) {
					console.log(ret);
					if (ret.status == 200) {
						Object.assign(formData, ret.data.ds[0]);
						// 判断是否存在Filepath字段，存在则处理文件数据
						if (ret.data.ds[0].hasOwnProperty("Filepath") && !!ret.data.ds[0].Filepath) {
							uploadFile_list.value = ret.data.ds[0].Filepath.split(",").map((item : any) => {
								// 判断当前地址是否存在http
								return mainStore.getReadyStaticUrl(item);
							});
							console.log(uploadFile_list.value);
						};

						formData.IsLinear = ret.data.ds[0]['IsLinear'] == 1 ? '是' : '否';
						formData.IsLinearID = ret.data.ds[0]['IsLinear'];
						// 赋值工艺路线
						RoutingData.value = ret.data.ds1;
						// 拼接工艺路线数据
						let GetRouting = ret.data.ds1.map((item : any) => {
							return item.ProcedureName;
						});
						formData.Routing = GetRouting.join('、');
						// 赋值用料清单
						MaterialsList.value = ret.data.ds2;
						formData.MaterialsListTotal = ret.data.ds2.length;
						formData.StartTime = dateFormat(formData.DueStartDate);
						formData.EndTime = dateFormat(formData.DueEndDate);
						callBack && callBack();

						uni.$utils.hideLoading();
						enabledSubmitBtn.value = true;
						loadingConfig.show = false;
						loadingConfig.text = "正在渲染";
						baseFormRef.value?.validate();
					} else {
						uni.$utils.layer.alert(ret.data?.ds[0]?.msg);
					};
				},
				fail(error : any) {
					console.log(error);
					uni.$utils.layer.alert(JSON.stringify(error))
				}
			});

		}
	};

	// 保存
	function saveRow(str : string) {
		if (!enabledSubmitBtn.value) return;
		loadingConfig.text = "正在校验";
		loadingConfig.show = true;
		enabledSubmitBtn.value = false;

		baseFormRef.value?.validate().then(async (res : any) => {
			loadingConfig.text = "校验成功，准备提交";
			let ProcessRouteIDs = [] as any,
				ProcessRouteDeIDs = [] as any,
				ProcedureIDs = [] as any,
				WoFWorkshopIDs = [] as any,
				EquipmentTypeIDs = [] as any,
				MoludTypeIDs = [] as any,
				LabourCost = [] as any,
				ManHour = [] as any,
				HourGJ = [] as any,
				Outsource = [] as any,

				BomIDs = [] as any,
				BomDeIDs = [] as any,
				WoPartIDs = [] as any,
				WoPROCIDs = [] as any,
				ProductSunIDs = [] as any,
				ParentNums = [] as any,
				SunNumes = [] as any,
				LossRatios = [] as any;

			RoutingData.value.forEach((item : any) => {
				ProcessRouteIDs.push(item.ProcessRouteID || 0);
				ProcessRouteDeIDs.push(item.ProcessRouteDeID || 0);
				ProcedureIDs.push(item.ProcedureID || 0);
				WoFWorkshopIDs.push(item.FWorkshopID || formData.FWorkshopID);
				EquipmentTypeIDs.push(item.EquipmentTypeID || 0);
				MoludTypeIDs.push(item.MoludTypeID || 0);
				LabourCost.push(item.LabourCost || 0);
				ManHour.push(item.ManHour || 0);
				HourGJ.push(item.HourGJ || 0);
				Outsource.push(Number(item.Outsource) || 0);
				WoPROCIDs.push(item.WoPROCID || 0);
			});
			MaterialsList.value.forEach((item : any) => {
				BomIDs.push(item.BomID || 0);
				BomDeIDs.push(item.BomDeID || 0);
				WoPartIDs.push(item.WoPartID || 0);
				ProductSunIDs.push(item.ProductID || 0);
				ParentNums.push(item.ParentNum || 0);
				SunNumes.push(item.SunNume || 0);
				LossRatios.push(item.LossRatio || 0);
			});
			let obj = {
				WoOrderID: !uni.$utils.isEmpty(formData.WoOrderID) ? formData.WoOrderID :
					0, // 工单ID
				ProductID: formData.ProductID, // 产品ID

				ProcessRouteID: ProcessRouteIDs.join('~'), // 工艺路线主表ID
				ProcessRouteDeID: ProcessRouteDeIDs.join('~'), // 工艺路线子表ID
				ProcedureID: ProcedureIDs.join('~'), // 工序ID

				WoFWorkshopID: WoFWorkshopIDs.join('~'), // 工序生产车间
				EquipmentTypeID: EquipmentTypeIDs.join('~'), // 设备类型
				MoludTypeID: MoludTypeIDs.join('~'), // 模具类型
				LabourCost: LabourCost.join('~'), // 计件单价
				ManHour: ManHour.join('~'), // 工时
				HourGJ: HourGJ.join('~'), // 工时工价
				Outsource: Outsource.join('~'), // 是否外协

				FWorkshopID: formData.FWorkshopID, // 工作中心
				IsLinear: formData.IsLinearID, // 是否线性
				FPlanQty: formData.FPlanQty, // 计划数量
				DueStartDate: dateFormat(formData.StartTime), // 开始时间
				DueEndDate: dateFormat(formData.EndTime), // 结束时间


				BomID: BomIDs.join('~'), // Bom主表ID
				BomDeID: BomDeIDs.join('~'), // Bom子表ID
				ProductSunID: ProductSunIDs.join('~'), // 配件ID
				ParentNum: ParentNums.join('~'), // 父件基数
				SunNume: SunNumes.join('~'), // 子件用量
				LossRatio: LossRatios.join('~'), // 损耗率%

				FilePath: formData.FilePath, // 文件地址
				Comment: formData.Comment, // 备注
				WoPROCID: WoPROCIDs.join('~'), // gylx

				WoPartID: WoPartIDs.join('~'), // bom

			};



			switch (str) {
				case "create":
				case "edit":
				case "Audit":
					loadingConfig.text = "正在提交";
					const save_back = await request({
						url: 'XGD_SubmitAndUpdate',
						method: 'POST',
						data: obj
					});
					console.log(save_back);

					// 判断接口调用状态
					if (save_back.status == 200) {
						loadingConfig.text = "提交成功";
						// 返回的数据中可能存在状态值Status，用于校验提交的数据的状态
						if (save_back.data?.ds.length && save_back.data?.ds[0]?.Status == 200) {

							// 获取主键ID
							formData.WoOrderID = save_back.data.ds[0].WoOrderID;
							// 判断当前走的是否是审核步骤
							switch (str) {
								case "Audit":
									onAuditBtn('context')
									break;
								default:
									// 调用修改查询接口，赋值数据
									refreshPage(() => {
										// 触发监听
										uni.$emit('refreshPage_ticket');
									});
									break;
							}

						}

					}


					break;
				default:
					break;
			}




		}).catch((error : any) => {
			console.log(error)
			loadingConfig.show = false;
			enabledSubmitBtn.value = true;
			uni.$utils.msg("请完善表单信息！")
		})
	};

	// 发放派工
	function openDispatchBtn() {
		console.log(formData);
		ticketStore.createTicket_routing = {
			// RoutingData: RoutingData.value,
			// FWorkshop: {
			// 	FWorkshopName: formData.FWorkshopName,
			// 	FWorkshopID: formData.FWorkshopID,
			// },
			ProgressList: RoutingData.value,
			form: formData,
			listenName: baseScreenListenName.value
		};

		uni.navigateTo({
			url: '/st_ticket/page_dispatch/dispatch-create'
		})
	};
	// 审核、撤审按钮
	function onAuditBtn(target : string) {
		// 当属于按钮触发时，使用按钮状态控制
		if (target == "btn") {
			if (!enabledSubmitBtn.value) return;
			enabledSubmitBtn.value = false;
		}

		// refreshPage
		let type = formData.Approve ? -1 : 1;
		loadingConfig.show = true;
		loadingConfig.text = formData.Approve ? '正在撤审' : '正在审核';
		request({
			config: {
			},
			url: 'XGD_ApproveAndSend',
			method: 'POST',
			data: {
				FType: '审核',
				approveFType: type,
				WoOrderID: formData.WoOrderID,
				approvalType: 0,
				LZMNum: 0,
			},
			success(ret : any) {
				console.log(ret);

				if (ret.status == 200) {
					if (ret.data?.ds.length && ret.data?.ds[0]?.RZT == 500) {

						loadingConfig.show = false;
						uni.$utils.hideLoading();
						uni.$utils.layer.alert(ret.data.ds[0].RMS);
					} else {
						refreshPage(() => {
							uni.$utils.hideLoading();
							// 触发监听
							uni.$emit('refreshPage_ticket');
							let msg = type == 1 ? "审核成功" : "已撤审";

							loadingConfig.text = msg;
							setTimeout(() => {
								loadingConfig.show = false;
							}, 500);
						})
					}
				} else {

					loadingConfig.show = false;
					enabledSubmitBtn.value = true;
					uni.$utils.layer.alert(JSON.stringify(ret));
				}
			}
		});

	}

	onAllComplete((ret : string) => {
		console.log("请求完成");
		// console.log(ret);
		// uni.$utils.hideLoading();
		// enabledSubmitBtn.value = true;
		// loadingConfig.show = false;
		// loadingConfig.text = "正在渲染";
	})

	onLoad((option : any) => {
		if (!uni.$utils.isEmpty(option)) {
			formData.WoOrderID = option.WoOrderID;
			refreshPage();
		} else {
			formData.WoOrderID = 0;
			enabledSubmitBtn.value = true;
		}

	})


	onMounted(() => {
		// #ifdef MP-WEIXIN
		baseFormRef.value.setRules(rules)
		// #endif
		enabledSubmitBtn.value = true;
	})

	onReady(() => {

		enabledSubmitBtn.value = true;
		uni.$on(baseScreenListenName.value, (ret : any) => {
			console.log(ret);
			const { titleName } = ret;

			switch (titleName) {
				case "产品":
					Object.assign(formData, ret.data);
					// 根据产品获取工艺路线、用料清单 
					ProductToGetInfo();
					break;
				case "工作中心":
				case "线性":
					Object.assign(formData, ret.data);
					baseFormRef.value?.validate();
					break;
				case "工艺路线":
					const rData = JSON.parse(JSON.stringify(ticketStore.createTicket_routing.RoutingData));
					RoutingData.value = rData;
					let GetRouting = rData.map((item : any) => {
						return item.ProcedureName
					});
					formData.Routing = GetRouting.join('、');
					setTimeout(() => {
						baseFormRef.value?.validate();
						ticketStore.createTicket_routing = {};
					}, 300)
					break;

				case "用料清单":
					const MaterialsList_Back = uni.$utils.deepClone(ticketStore.createTicket_Materials);
					MaterialsList.value = MaterialsList_Back.MaterialsList;
					formData.MaterialsListTotal = MaterialsList_Back.MaterialsList.length;

					setTimeout(() => {
						ticketStore.createTicket_Materials = {};
					}, 0);
					break;
				default:
					break;
			}
		})
	})

	onUnload(() => {

		uni.$off(baseScreenListenName.value);
	});
</script>

<style lang="scss">
	.page__content {
		height: 100vh;

		&__main {}

		:deep(.u-form) {
			padding: 0 20rpx;
			background-color: #fff;

			.iptView {
				width: 100%;
			}

			// 处理 up-input 在小程序下样式穿透
			:deep(.u-input) {
				font-size: 28rpx;
				width: 100% !important;
			}
		}

		&__time-choice {
			display: flex;
			flex-direction: column;
			margin-top: 10rpx;
		}

		&__time-box {
			display: flex;
			align-items: center;
			justify-content: space-between;
		}

		&__time-start,
		&__time-end {
			flex: 1;
			display: flex;
			flex-direction: column;
			color: #333;
			font-size: 28rpx;
		}

		&__time-icon {
			margin: 0 20rpx;
		}

		&__materials {
			display: flex;
			align-items: center;
			font-size: 28rpx;
			color: #333;
		}

		&__materials-count {
			color: #51d0d0;
			font-weight: 600;
			margin: 0 8rpx;
			font-size: 28rpx;
		}

		&__materials-empty {
			color: #999;
			font-size: 28rpx;
		}

		&__btns {
			padding: 6px 15px;
			display: flex;
			align-items: center;
			justify-content: flex-end;
			background-color: #fff;
		}

		&__btn {
			width: 80%;

			&--primary {
				background-color: #51d0d0;
				color: #fff;
			}
		}


	}
</style>